package com.songyuquan.webcs.controller;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.songyuquan.webcs.mapper.IntegralsMapper;
import com.songyuquan.webcs.mapper.OrderMapper;
import com.songyuquan.webcs.pojo.*;
import com.songyuquan.webcs.service.*;
import com.songyuquan.webcs.vo.CartVO;
import com.songyuquan.webcs.vo.OrdersVO;
import com.songyuquan.webcs.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Random;

/**
 * 支付控制器
 */
@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private PayService payService;

    @Autowired
    private UserAddressService userAddressService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CartService cartService;

    @Autowired
    private ProductService productService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private IntegralsMapper integralsMapper;

    @PostMapping("/productAlipay")
    public String productAlipay(
            Float cost,
            String userAddress,
            String address,
            String remark,
            HttpSession session
    ) throws AlipayApiException {
        User user = (User) session.getAttribute("user");
        //地址
        String defaultAddress = "";
        if (userAddress.equals("newAddress")) {
            UserAddress address1 = new UserAddress();
            address1.setAddress(address);
            address1.setRemark(remark);
            address1.setUserId(user.getId());
            address1.setIsdefault(1);
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("isdefault", 1);
            UserAddress isDefault = userAddressService.getOne(wrapper);
            isDefault.setIsdefault(0);
            userAddressService.updateById(isDefault);
            userAddressService.save(address1);
            defaultAddress = address;
        } else {
            defaultAddress = userAddress;
        }
        //订单编号
        String seriaNumber = null;
        try {
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < 32; i++) {
                result.append(Integer.toHexString(new Random().nextInt(16)));
            }
            seriaNumber = result.toString().toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //积分
        Integer integrals = 0;
        List<CartVO> cartVOList = cartService.findAllCartVOByUserId(user.getId());
        for (CartVO cartVO : cartVOList) {
            Product product = productService.getById(cartVO.getProductId());
            integrals += product.getIntegral() * cartVO.getQuantity();
        }
        //订单信息
        OrdersVO ordersVO = new OrdersVO();
        ordersVO.setCost(cost);
        ordersVO.setIntegral(integrals);
        ordersVO.setUserAddress(defaultAddress);
        ordersVO.setUserId(user.getId());
        ordersVO.setLoginName(user.getLoginName());
        ordersVO.setSerialnumber(seriaNumber);
        //将用户信息和商品信息存到redis中
        ValueOperations valueOperations = redisTemplate.opsForValue();
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        valueOperations.set("user", userVO);
        valueOperations.set("orders", ordersVO);
        valueOperations.set("carList", cartVOList);
        //调用支付宝
        AlipayBean order = new AlipayBean();
        order.setOut_trade_no(seriaNumber);
        order.setSubject(user.getUserName() + "用户订单");
        order.setTotal_amount(String.valueOf(cost));
        order.setDescription("商品购买");
        return payService.aliPay(order);
    }

    @GetMapping("/settlement3")
    public ModelAndView settlement3(HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("settlement3");
        ValueOperations valueOperations = redisTemplate.opsForValue();

        User user = (User) session.getAttribute("user");
        UserVO userVO = null;
        if (user == null) {
            user = new User();
            userVO = (UserVO) valueOperations.get("user");
            BeanUtils.copyProperties(userVO, user);
            session.setAttribute("user", user);
        }
        //删除购物车信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", user.getId());
        cartService.remove(queryWrapper);
        //订单页数据
        OrdersVO ordersVO = (OrdersVO) valueOperations.get("orders");
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersVO, orders);
        orders.setGoods("未发货");
        orderMapper.insertReturnId(orders);
        Integer orderId = orders.getId();
        List<CartVO> cartVOList = (List<CartVO>) valueOperations.get("carList");
        OrderDetail orderDetail = null;
        //商品详情页数据
        for (CartVO cartVO : cartVOList) {
            orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setProductId(cartVO.getProductId());
            orderDetail.setQuantity(cartVO.getQuantity());
            orderDetail.setCost(cartVO.getCost());
            Product product = productService.getById(cartVO.getProductId());
            orderDetail.setIntegral(cartVO.getQuantity() * product.getIntegral());
            orderDetailService.save(orderDetail);
        }
        //积分信息保存
        Integrals integrals = null;
        QueryWrapper queryWrapper5 = new QueryWrapper();
        queryWrapper5.eq("user_id", user.getId());
        integrals = integralsMapper.selectOne(queryWrapper5);
        if (integrals == null) {
            integrals = new Integrals();
            integrals.setIntegral(orders.getIntegral());
            assert userVO != null;
            integrals.setUserId(userVO.getId());
            integralsMapper.insert(integrals);
        } else {
            integrals.setIntegral(integrals.getIntegral() + orders.getIntegral());
            integralsMapper.updateById(integrals);
        }
        modelAndView.addObject("orders", ordersVO);
        modelAndView.addObject("cartList", cartService.findAllCartVOByUserId(userVO.getId()));
        return modelAndView;
    }


    @GetMapping("/settlementIntegralPage/{productId}/{quantity}")
    public ModelAndView settlementIntegralPage(
            HttpSession session,
            @PathVariable("productId") Integer productId,
            @PathVariable("quantity") Integer quantity
    ) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("settlementIntegral");
        User user = (User) session.getAttribute("user");
        Product product = productService.getById(productId);
        modelAndView.addObject("product", product);
        modelAndView.addObject("quantity", quantity);
        modelAndView.addObject("totalIntegrals", quantity * product.getIntegral());

        modelAndView.addObject("cartList", cartService.findAllCartVOByUserId(user.getId()));

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", user.getId());
        modelAndView.addObject("addressList", userAddressService.list(queryWrapper));
        return modelAndView;
    }


    @PostMapping("/integralsAlipay")
    public ModelAndView integralsAlipay(
            Integer productId,
            Integer quantity,
            String userAddress,
            String address,
            String remark,
            HttpSession session
    ) throws AlipayApiException {

        User user = (User) session.getAttribute("user");
        Product product = productService.getById(productId);
        product.setStock(product.getStock() - quantity);

        productService.updateById(product);

        //地址
        String defaultAddress = "";
        if (userAddress.equals("newAddress")) {
            UserAddress address1 = new UserAddress();
            address1.setAddress(address);
            address1.setRemark(remark);
            address1.setUserId(user.getId());
            address1.setIsdefault(1);
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("isdefault", 1);
            UserAddress isDefault = userAddressService.getOne(wrapper);
            isDefault.setIsdefault(0);
            userAddressService.updateById(isDefault);
            userAddressService.save(address1);
            defaultAddress = address;
        } else {
            defaultAddress = userAddress;
        }

        //订单编号
        String seriaNumber = null;
        try {
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < 32; i++) {
                result.append(Integer.toHexString(new Random().nextInt(16)));
            }
            seriaNumber = result.toString().toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //积分
        Integer integrals = product.getIntegral() * quantity;

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", user.getId());
        Integrals integrals1 = integralsMapper.selectOne(queryWrapper);
        integrals1.setIntegral(integrals1.getIntegral() - integrals);

        integralsMapper.updateById(integrals1);

        Orders orders = new Orders();
        orders.setGoods("未发货");
        orders.setCost(0F);
        orders.setUserId(user.getId());
        orders.setLoginName(user.getLoginName());
        orders.setUserAddress(defaultAddress);
        orders.setIntegral(-integrals);
        orders.setSerialnumber(seriaNumber);

        orderMapper.insertReturnId(orders);
        Integer ordersId = orders.getId();

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(ordersId);
        orderDetail.setProductId(product.getId());
        orderDetail.setQuantity(quantity);
        orderDetail.setCost(0F);
        orderDetail.setIntegral(integrals);

        orderDetailService.save(orderDetail);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("settlement4");
        modelAndView.addObject("seriaNumber", seriaNumber);
        modelAndView.addObject("integrals", integrals);
        modelAndView.addObject("defaultAddress", defaultAddress);
        modelAndView.addObject("cartList", cartService.findAllCartVOByUserId(user.getId()));

        return modelAndView;

    }
}

